<template>
  <div class="doctor-tell">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input
        v-model="searchName"
        placeholder="请输入病人编号搜索"
        class="search-input"
        clearable
        @input="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input> 
      <el-button type="primary" @click="handleAdd">添加医嘱</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="filteredTableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column prop="id" label="序号" width="80" />
      <el-table-column prop="bedCode" label="床位" width="120">
        <template #default="scope">
          {{ formatBedCode(scope.row.bedCode) }}
        </template>
      </el-table-column>
      <el-table-column prop="patientCode" label="病人" width="120" />
      <el-table-column prop="doctorContent" label="医嘱内容" />
      <el-table-column prop="doctorSTime" label="医嘱开始日期" width="180">
        <template #default="scope">
          {{ scope.row.doctorSTime ? new Date(scope.row.doctorSTime).toLocaleDateString() : '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="doctorETime" label="医嘱结束日期" width="180" >
        <template #default="scope">
          {{ scope.row.doctorETime ? new Date(scope.row.doctorETime).toLocaleDateString() : '---' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120" >
         <template #default="scope">
          <el-tagb v-if="scope.row.isPublisher==0">未发布</el-tagb>
          <el-tagb v-if="scope.row.isPublisher==1">已发布</el-tagb>
         </template>
        
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            v-if="scope.row.isPublisher == 0"
            link
            type="primary"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <span v-else>---</span>
          <el-button
            v-if="scope.row.isPublisher == 0"
            link
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
            v-if="scope.row.isPublisher === 0"
            link
            type="success"
            @click="handlePublish(scope.row.id)"
          >
            发布
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑医嘱对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加医嘱' : '编辑医嘱'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="床位" prop="bedCode">
          <el-select v-model="form.bedCode" placeholder="请选择床位">
            <el-option v-for="item in getBedData" :label="item.bedCode" :value="item.wardCode" /> 
            <!-- <el-option  label="item.wardCode" value="item.bedCode" />  -->
          </el-select>
        </el-form-item>
        <el-form-item label="病人" prop="patientCode">
          <el-input v-model="form.patientCode" placeholder="请输入病人编号" />
        </el-form-item>
        <el-form-item label="医嘱内容" prop="doctorContent">
          <el-input
            v-model="form.doctorContent"
            type="textarea"
            placeholder="请输入医嘱内容"
          />
        </el-form-item>
        <el-form-item label="开始日期" prop="doctorSTime">
          <el-date-picker
            v-model="form.doctorSTime"
            type="date"
            placeholder="选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="结束日期" prop="doctorETime">
          <el-date-picker
            v-model="form.doctorETime"
            type="date"
            placeholder="选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import http from '@/api/http'
import * as signalR from '@microsoft/signalr'

interface FormType {
  id?: number
  doctorCode:string
  bedCode: string
  patientCode: string
  doctorContent: string
  doctorSTime: string
  doctorETime: string
  isPublisher: 0,
  isDelete: 0
}

// 搜索相关
const searchName = ref('')
const tableData = ref<FormType[]>([]) // 添加类型定义
const filteredTableData = ref<FormType[]>([]) // 添加类型定义

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref()
const form = ref<FormType>({
  bedCode: '',
  doctorCode:'',
  patientCode: '',
  doctorContent: '',
  doctorSTime: '',
  doctorETime: '',
  isPublisher: 0,
  isDelete: 0
})

// 表单验证规则
const rules = {
  bedCode: [{ required: true, message: '请选择床位', trigger: 'change' }],
  patientCode: [{ required: true, message: '请输入病人编号', trigger: 'blur' }],
  doctorContent: [{ required: true, message: '请输入医嘱内容', trigger: 'blur' }],
  doctorSTime: [{ required: true, message: '请选择开始日期', trigger: 'change' }]
}

// 登录用户信息
const loginUserName = ref('')

// 获取登录用户信息
const getLoginUserInfo = () => {
  const userStr = localStorage.getItem('user') 
  if (userStr) {
    const userObj = JSON.parse(userStr)
    loginUserName.value = userObj.userName || ''
  }
  // console.log(loginUserName.value)
}

// 处理搜索
const handleSearch = () => {
  if (!searchName.value) {
    // 如果搜索框为空，显示所有数据
    filteredTableData.value = tableData.value
    return
  }
  
  // 过滤包含搜索关键字的数据
  filteredTableData.value = tableData.value.filter(item => 
    item.patientCode?.toLowerCase().includes(searchName.value.toLowerCase())
  )
}

// 打开添加对话框
const handleAdd = () => {
  getBed();
  dialogType.value = 'add'
  form.value = {
    bedCode: '',
    doctorCode:'',
    patientCode: '',
    doctorContent: '',
    doctorSTime: '',
    doctorETime: '' ,
    isPublisher: 0,
    isDelete: 0
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row: FormType) => {
  getBed();
  dialogType.value = 'edit'
  form.value = {
    id: row.id,
    doctorCode:'',
    bedCode: row.bedCode,
    patientCode: row.patientCode,
    doctorContent: row.doctorContent,
    doctorSTime: row.doctorSTime,
    doctorETime: row.doctorETime,
    isPublisher: 0,
    isDelete: 0
  }
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (row: FormType) => {
  if (!row.id) {
    ElMessage.error('无效的医嘱ID')
    return
  }
  
  ElMessageBox.confirm(
    '确定要删除这条医嘱吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    deleteTell(row.id as number)
  })
}



// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      const formData = {
        ...form.value,
        doctorSTime: form.value.doctorSTime ? new Date(form.value.doctorSTime).toISOString() : '',
        doctorETime: form.value.doctorETime ? new Date(form.value.doctorETime).toISOString() : ''
      }

      if (dialogType.value === 'add') {
        addTell(formData)
      } else {
        editTell(formData)
      }
    }
  })
}

// API调用方法
// 添加医嘱
const addTell = (data: FormType) => {  
  data.doctorCode=loginUserName.value
  http.post('/api/DoctorManage/CreateTell', data)
    .then(res => {
      console.log(res)
      ElMessage.success('添加成功')
      dialogVisible.value = false
      showTell() // 刷新列表
    })
    .catch(err => {
      console.error(err)
      ElMessage.error('添加失败')
    })
}

// 删除医嘱
const deleteTell = (id: number) => {
  http.post('/api/DoctorManage/DeleteTell?id='+ id )
    .then(res => {
      console.log(res)
      ElMessage.success('删除成功')
      showTell() // 刷新列表
    })
    .catch(err => {
      console.error(err)
      ElMessage.error('删除失败')
    })
}

// 编辑医嘱
const editTell = (data: FormType) => {
  http.post('/api/DoctorManage/UpdateTell', data)
    .then(res => {
      console.log(res)
      ElMessage.success('更新成功')
      dialogVisible.value = false
      showTell() // 刷新列表
    })
    .catch(err => {
      console.error(err)
      ElMessage.error('更新失败')
    })
}

// 获取医嘱列表
const showTell = () => {
  http.get('/api/DoctorManage/GetTells')
    .then(res => {
      // console.log('医嘱列表:', res.data)
      tableData.value = res.data // 保存原始数据
      filteredTableData.value = res.data // 初始显示所有数据
    })
    .catch(err => {
      console.error(err)
      ElMessage.error('获取列表失败')
    })
}


// 处理发布
const handlePublish = (row: FormType) => {
  ElMessageBox.confirm(
    '确定要发布这条医嘱吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    }
  ).then(() => { 
    updatestatus(row)
  })
}



//修改发布状态
const updatestatus = async (id:any) => {
  try {
    const res = await http.post("/api/DoctorManage/Updatesatus?id="+id)
    if (res.status === true) {
      ElMessage.success('发布成功')
      await showTell()
      // 发送SignalR通知
      sendMessage()
    } else {
      ElMessage.error(res.message || '发布失败')
    }
  } catch (err) {
    console.error('发布失败:', err)
    ElMessage.error('发布失败')
  }
}

const getBedData=ref<any>([])
const getBed=()=>{
  http.get('/api/DoctorManage/GetBed')
  .then(res=>{
    console.log(res)
    getBedData.value=res.data
  })
}

// 格式化床位编码
const formatBedCode = (bedCode: string | number) => {
  if (!bedCode) return '';
  const num = parseInt(bedCode.toString());
  return `C${num < 10 ? '00' + num : num < 100 ? '0' + num : num}`;
}

// 监听搜索框变化
watch(searchName, () => {
  handleSearch()
})

// 建立连接
let connection:any = null

const initConnection = async () => {
  // 如果已经有连接，不需要重新建立
  if (connection) return
  
  try {
    connection = new signalR.HubConnectionBuilder()
      .withUrl('http://localhost:9991/chatHub')
      .withAutomaticReconnect()
      .build()
      
    // @ts-ignore
    connection.on('MessageInfo', function(message) {
      console.log('医生端收到消息:', message)
    })
    
    await connection.start()
    console.log('SignalR连接已建立')
  } catch (error) {
    console.error('SignalR连接失败:', error)
  }
}

// 发送消息函数
const sendMessage = async () => {
  try {
    if (!connection || connection.state !== signalR.HubConnectionState.Connected) {
      await initConnection()
    }
    
    if (connection && connection.state === signalR.HubConnectionState.Connected) {
      // @ts-ignore
      await connection.invoke('SendMessage')
      console.log('通知已发送')
    }
  } catch (error) {
    console.error('发送通知失败:', error)
  }
}

// 初始化连接
onMounted(async () => {
  showTell()
  getLoginUserInfo()
  await initConnection()
})

// 组件卸载时关闭连接
onUnmounted(() => {
  if (connection) {
    connection.stop()
  }
})



</script>

<style scoped>
.doctor-tell {
  padding: 20px;
}

.search-area {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}
</style>